/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ListarAmigos.java
 *
 * Created on 02-nov-2011, 19:13:00
 */
package Ventanas;

import Controladores.Memoria;
import Objetos.PropiedadesIP;
import ObjetosJpa.HistorialJpa;
import ObjetosJpa.MensajeJpa;
import ObjetosJpa.UsuarioJpa;
import Proxies.CtrlMovilWS;
import Proxies.CtrlMovilWSService;
import Proxies.CtrlUsuariosWS;
import Proxies.CtrlUsuariosWSService;
import Proxies.DataHistorial;
import Proxies.DataMensaje;
import Proxies.DataUsuarioArray;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.table.DefaultTableModel;
import javax.xml.namespace.QName;

/**
 *
 * @author Sebas
 */
public class ListarAmigos extends javax.swing.JDialog {

    private String mailUsr;
    boolean conectado;
    Principal principal;

    /** Creates new form ListarAmigos */
    public ListarAmigos(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public ListarAmigos(java.awt.Frame parent, boolean modal, String mailUsr, boolean conectado,Principal prin) {
        super(parent, modal);
        initComponents();
        this.mailUsr = mailUsr;
        this.conectado = conectado;
        this.principal = prin;
        if (this.conectado) {
            cargarAmigos();
        } else {
//            cargarAmigosMemoria();
            cargarJpa();
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtable_amigos = new javax.swing.JTable();
        historial = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        listHistorial = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("LISTAR AMIGOS DEL USUARIO");

        jLabel1.setText("LISTA DE AMIGOS");

        jtable_amigos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nick", "Correo", "Imagen", "Conectado?"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jtable_amigos);

        historial.setText("VER HISRTORIAL DE CONVERSACION");
        historial.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                historialActionPerformed(evt);
            }
        });

        jScrollPane2.setViewportView(listHistorial);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(113, 113, 113)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(historial)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 306, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(80, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addComponent(historial)
                .addGap(35, 35, 35)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(51, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void historialActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_historialActionPerformed
        // TODO add your handling code here:

        String select = jtable_amigos.getValueAt(jtable_amigos.getSelectedRow(), 1).toString();
        PropiedadesIP props = PropiedadesIP.getInstance();
        String IP = props.getServidorCentralIP();
        URL dir = null;
        try {
            dir = new URL(IP + "CtrlUsuarios?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(ListarAmigos.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNa = new QName("http://WebServices/", "CtrlUsuariosWSService");
        CtrlUsuariosWS ctrlUsr = new CtrlUsuariosWSService(dir, qNa).getCtrlUsuariosWSPort();
        DataHistorial dhist;
        HistorialJpa histjpa = null;
        DefaultListModel model = new DefaultListModel();
        if (!conectado) {
            dhist = principal.getHistorial(select);
            Collection<HistorialJpa> listHist = principal.getUsuarioJpa().getHistorial();
            Iterator<HistorialJpa> it = listHist.iterator();

            boolean encontro = false;

             while (it.hasNext()&& !encontro)
             {
                histjpa = it.next();
                if(histjpa.getIdAmigo()!=null)
                 if(histjpa.getIdAmigo().equals(select))
                     encontro = true;
             }


            if (histjpa != null) {
                Iterator<MensajeJpa> it2 = histjpa.getMensajes().iterator();

                while (it2.hasNext()) {

                    MensajeJpa mens = it2.next();
                    model.add(model.size(), "<html><b>" + mens.getEmisor() + ": </b> " + mens.getMsj() + "</html>");
                }
            }
         
         
        } else {
            dhist = ctrlUsr.getHistorial(mailUsr, select);

        if (dhist != null) {
            Iterator<DataMensaje> it = dhist.getMensajes().iterator();

            while (it.hasNext()) {

                DataMensaje mens = it.next();
                model.add(model.size(), "<html><b>" + mens.getEmisor() + ": </b> " + mens.getMsj() + "</html>");

            }
        }
        }
        listHistorial.setModel(model);



    }//GEN-LAST:event_historialActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListarAmigos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListarAmigos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListarAmigos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListarAmigos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                ListarAmigos dialog = new ListarAmigos(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton historial;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jtable_amigos;
    private javax.swing.JList listHistorial;
    // End of variables declaration//GEN-END:variables

    private void cargarAmigos() {

        PropiedadesIP props = PropiedadesIP.getInstance();
        String IP = props.getServidorCentralIP();
        URL dir = null;
        try {
            dir = new URL(IP + "CtrlUsuarios?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(ListarAmigos.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNa = new QName("http://WebServices/", "CtrlUsuariosWSService");
        CtrlUsuariosWS ctrlUsr = new CtrlUsuariosWSService(dir, qNa).getCtrlUsuariosWSPort();

        URL dirMovil = null;
        try {
            dirMovil = new URL(IP + "CtrlMovil?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(ListarAmigos.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNaMovil = new QName("http://WebServices/", "CtrlMovilWSService");
        CtrlMovilWS ctrlMov = new CtrlMovilWSService(dirMovil, qNaMovil).getCtrlMovilWSPort();
        DataUsuarioArray amis = ctrlUsr.listarDAmigos(mailUsr);
        DefaultTableModel model = (DefaultTableModel) jtable_amigos.getModel();
        model.setRowCount(0);
        if (!amis.getItem().isEmpty()) {
            Object[] fila = new Object[4];
            Iterator<Proxies.DataUsuario> itera = amis.getItem().iterator();
            Proxies.DataUsuario usr;
            while (itera.hasNext()) {
                usr = itera.next();
                fila[0] = usr.getNick();
                fila[1] = usr.getCorreo();
                fila[2] = usr.getImagen();
                boolean estaConectado = ctrlMov.isConectadoUsuario(usr.getCorreo());
                fila[3] = (estaConectado) ? "CONECTADO" : "NO CONECTADO";
                model.addRow(fila);
            }
        }

    }

    private void cargarAmigosMemoria() {


        Memoria ctrlUsr = Memoria.getInstance();
        
        DataUsuarioArray amis = ctrlUsr.getAmigos();
        DefaultTableModel model = (DefaultTableModel) jtable_amigos.getModel();
        model.setRowCount(0);
        if (!amis.getItem().isEmpty()) {
            Object[] fila = new Object[4];
            Iterator<Proxies.DataUsuario> itera = amis.getItem().iterator();
            Proxies.DataUsuario usr;
            while (itera.hasNext()) {
                usr = itera.next();
                fila[0] = usr.getNick();
                fila[1] = usr.getCorreo();
                fila[2] = usr.getImagen();
                model.addRow(fila);
            }
        }
    }
    private void cargarJpa(){
        
        
        UsuarioJpa usuJpa = principal.getUsuarioJpa();
        if(!usuJpa.isPrimeravez()){
        
        Collection<UsuarioJpa> amis = usuJpa.getAmigos();
        DefaultTableModel model = (DefaultTableModel) jtable_amigos.getModel();
        model.setRowCount(0);
        if (!amis.isEmpty()) {
            Object[] fila = new Object[4];
            Iterator<UsuarioJpa> itera = amis.iterator();
            UsuarioJpa usr;
            while (itera.hasNext()) {
                usr = itera.next();
                fila[0] = usr.getNick();
                fila[1] = usr.getCorreo();
                fila[2] = usr.getImagen();
                model.addRow(fila);
            }
        }
        
    }
    else cargarAmigosMemoria();
    }
}
